package be.roam.drest.twitter;

import java.util.Set;

import org.apache.commons.lang.StringEscapeUtils;

import be.roam.drest.service.twitter.TwitterService;
import be.roam.drest.service.twitter.TwitterStatus;
import be.roam.util.CollectionsUtil;

public class Twitter {

	/**
	 * Main stuff...
	 *
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		boolean publicTimeline = (args.length > 0 && "public".equals(args[0]));
		if (args.length < 3 && !publicTimeline) {
			System.out.println("Arguments: <email|screen name> <password> <method>");
			System.out.println("Possible methods:");
			System.out.println("\t- public (in this case email/screen name & password can be omitted)");
			System.out.println("\t- self_friends");
			System.out.println("\t- update <status>");
			return;
		}
		if (publicTimeline) {
			// The public timeline doesn't require an email or screen name and password
			TwitterService service = new TwitterService();
			showTimeline(service.getPublicTimeline());
		} else {
			// No longer using the public timeline: set up a service for the user with the given email/screen name and password
			TwitterService service = new TwitterService(args[0], args[1]);
			if ("self_friends".equals(args[2])) {
				showTimeline(service.getSelfAndFriendsTimeline());
			} else if ("update".equals(args[2])) {
				update(service, args[3]);
			}
		}
	}

	/**
	 * Updates the Twitter status of the current user.
	 *
	 * @param service the Twitter service
	 * @param string the status message
	 * @throws Exception no fancy exception handling in this example
	 */
	private static void update(TwitterService service, String string) throws Exception {
		service.update(string);
	}

	private static void showTimeline(Set<TwitterStatus> set) {
		if (CollectionsUtil.isNullOrEmpty(set)) {
			System.out.println("Nothing has been said");
		}
		for (TwitterStatus status : set) {
			// Example output: "Five minutes ago, Drest said: Man, this stuff is nice!"
			System.out.println(status.getRelativeCreated() + ", " + status.getUser().getScreenName() + " said: " + StringEscapeUtils.unescapeHtml(status.getText()));
		}
	}

}
